package com.wans.easyuibackend.exception.handler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wans.easyuibackend.exception.data.DataFormatException;
import com.wans.easyuibackend.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice
@Slf4j
public class DataFormatExceptionHandler {

    @ExceptionHandler(value = DataFormatException.class)
    public ResponseEntity<String> dataFormatException(DataFormatException e) throws JsonProcessingException {
        Result result = new Result(Integer.parseInt(e.getStatus()), e.getMessage(), null);
        //new ObjectMapper().writeValueAsString(result) 把类转为json字符串
        System.out.println(new ObjectMapper().writeValueAsString(result));
        log.info("数据格式异常返回的数据->{}", ResponseEntity.status(Integer.parseInt(e.getStatus())).body(new ObjectMapper().writeValueAsString(result)));
        return ResponseEntity.status(Integer.parseInt(e.getStatus())).body(new ObjectMapper().writeValueAsString(result));
    }

    @ExceptionHandler({MethodArgumentNotValidException.class})
    public ResponseEntity<String> dateFormatException(MethodArgumentNotValidException e) {
        //日期数据异常
        log.info("日期数据异常");
        e.printStackTrace();
        //406	Not Acceptable	服务器无法根据客户端请求的内容特性完成请求
        return ResponseEntity.status(HttpStatus.NOT_ACCEPTABLE).body("日期格式有误");
    }
}
